#include "GameManager.h"

#include "_Global/Socket/ClientSocket.h"
#include "GamePlatform.h"


//#include <QtCore> //包含所有常用
#include <QQmlApplicationEngine>
#include <QQmlContext>
#include <QQuickWindow>
#include <QQuickView>
#include <QMessageBox>

GameManager::GameManager(QObject *parent) :
    QObject(parent), m_ConfigFile(FIXLOCALPATH_W("Config.cfg"))
{
    m_pGameWindow = nullptr;
    m_pGameCore = nullptr;
    m_pUserInfo = nullptr;
    m_pWordLib = nullptr;
    m_pInfoSocket = nullptr;
    m_pGameSocket = nullptr;

    m_pAppQmlEngine = nullptr;
}


GameManager::~GameManager()
{
    if(m_pAppQmlEngine != nullptr)
    {
        delete m_pAppQmlEngine;
        m_pAppQmlEngine = nullptr;
    }
    if(m_pUserInfo != nullptr)
    {
        delete m_pUserInfo;
        m_pUserInfo = nullptr;
    }
    if(m_pGameCore != nullptr)
    {
        delete m_pGameCore;
        m_pGameCore = nullptr;
    }
    if(m_pWordLib != nullptr)
    {
        delete m_pWordLib;
        m_pWordLib = nullptr;
    }
    if(m_pInfoSocket != nullptr)
    {
        delete m_pInfoSocket;
        m_pInfoSocket = nullptr;
    }
    if(m_pGameSocket != nullptr)
    {
        delete m_pGameSocket;
        m_pGameSocket = nullptr;
    }
}

bool GameManager::InitOnce()
{
    //QML中可以使用下列类的 枚举
    //qmlRegisterType<_BaseObject>("com.leamus.gamedata",1,0,"BasePokeClass");
    qmlRegisterType<_Pai>("com.leamus.gamedata",1,0,"PokeClass");
    qmlRegisterType<_WuJiang>("com.leamus.gamedata",1,0,"WuJiangClass");
    qmlRegisterType<_Player>("com.leamus.gamedata",1,0,"PlayerClass");
    //qmlRegisterType<_JiNeng>("com.leamus.gamedata",1,0,"JiNengClass");
    qmlRegisterUncreatableType<Game>("com.leamus.gamedata",1,0,"GameClass","Error Create Game Class");
    qmlRegisterUncreatableType<UserInfo>("com.leamus.gamedata",1,0,"UserInfoClass","Error Create UserInfo Class");
    qmlRegisterUncreatableType<GameManager>("com.leamus.gamedata",1,0,"GameManagerClass","Error Create GameManager Class");


    //要在 信号/槽/属性 的参数中使用，或者qml中使用下列类型的函数或数据，则注册一下！字符串名不能随意更改!
    /*
     * 1.enum类型:
     *      如果信号槽的参数要使用Q_ENUMS或Q_FLAGS,需要注册一下!
     *      注册方法:如果有 类前缀,参数中不能使用 类前缀!!!比如只能:
     *          qRegisterMetaType<[类名::]enum名>("enum名");
     *      注意:如果enum类型是全局的,则在QML中的值是QVariant!?
     * 2.类 类型:
     *      QML中需要使用其类的函数,或信号槽的参数中需要使用其类型,则需要注册一下:
     *      注册方法:如果有 类前缀,参数中必须要有 类前缀!!!比如:
     *          qRegisterMetaType<[类名::]类名>("[类名::]类名");
    */
    qRegisterMetaType<QObjectList>("QObjectList");      //qml中使用其函数
    qRegisterMetaType<_BaseObject::_ObjType>("_ObjType");  //信号/槽参数中使用
    qRegisterMetaType<_BaseObject::_Flags>("_Flags");
    //qRegisterMetaType<_WuJiang::_Value>("_Value");
    //qRegisterMetaType<GameCore::_GameButtonValue>("_GameButtonValue");
    qRegisterMetaType<GameCore::_GameStatus>("_GameStatus");
    qRegisterMetaType<_ClientGameStatus>("_ClientGameStatus");
    //qRegisterMetaType<_JiNeng>("_JiNeng");




    //pGameThread = new QThread(this);

    m_pGameCore = new Game(this);
    m_pUserInfo = new UserInfo(this);


    //m_pGameCore->pConfig = &config;
    //m_pUserInfo->pConfig = &config;



    m_pInfoSocket = new TcpSocket(this);
    m_pUserInfo->m_pInfoSocket = m_pInfoSocket;

    m_pGameSocket = new TcpSocket(this);
    m_pUserInfo->m_pGameSocket = m_pGameCore->m_pGameSocket = m_pGameSocket;

    m_pInfoSocket->m_baPackageHeaderFlag.setRawData("LMS",3);
    m_pGameSocket->m_baPackageHeaderFlag.setRawData("LMS",3);

    m_pGameSocket->startKeepAlive(10000, "H", 1);


//读取游戏配置(Sqlite)
    m_pWordLib = m_pUserInfo->m_pWordLib = m_pGameCore->m_pWordLib = new WordLib(this);

    while(1)
    {
        if(!LoadDatabase())
            return false;

        int ret = CheckConfig();
        if(ret > 0)
            continue;
        else if(ret < 0)
            return false;


        if(m_mapGameConfig.value("LoginUserPass", QString("")).toString().isEmpty())
        {
            m_mapGameConfig["rememberPassword"] = false;
        }
        else
            m_mapGameConfig["rememberPassword"] = true;


        //SaveConfigToDb("111","333");
        //DeleteConfigToDb("111");
        break;
    }

//读取配置(文件)
    m_ConfigFile.readConfigFile(m_mapGameConfig);
    //qDebug() << "m_ConfigFile" << m_ConfigFile.configHash;

    /*
    if(m_mapGameConfig.contains(key))
    {
        m_mapGameConfig[key] = value;
    }*/

//配置设置
    m_pInfoSocket->m_strIP = m_mapGameConfig.value("ServerIP", QVariant::fromValue(QString("server.yingyusha.com"))).toString();
    m_pInfoSocket->m_unPort = m_mapGameConfig.value("ServerPort", QVariant::fromValue(8806)).toInt();
    m_pGameCore->m_nGameRandom = m_mapGameConfig.value("Random", QVariant::fromValue(-1)).toInt();

    m_pGameCore->m_nGameMessageDelay = m_mapGameConfig.value("GameMessageDelay", QVariant::fromValue(1500)).toInt();

    qDebug() << m_pInfoSocket->m_strIP << m_pInfoSocket->m_unPort;
    //qDebug() << "config" << config.configHash;


//UserInfo:
    connect(m_pUserInfo,&UserInfo::s_SendCodeDataToServer,this,[=](TcpSocket* pSocket,QByteArray ba)
    {
        qDebug() << "数据长度:" << ba.length();
        NetLog(ba,true);
        SendWithCode(pSocket, ba);
    });




//socket信号

    //Socket已连接
    connect(m_pInfoSocket,&TcpSocket::s_connected,this,[=]()
    {
        //if(m_LoginInfo.m_ClientStatus == UserInfo::Client_IsLoginingInfoServer ||
        //    m_LoginInfo.m_ClientStatus == UserInfo::Client_IsRegisteringInfoServer)

        //m_pUserInfo->send();
        //m_pUserInfo->m_pInfoSocket->sendCache();
        m_pInfoSocket->send(false);
    });

    //Socket已连接
    connect(m_pGameSocket,&TcpSocket::s_connected,this,[=]()
    {
        //m_pUserInfo->m_pGameSocket->clearData();
        m_pGameSocket->send(false);
    });


    //连接主机错误
    connect(m_pInfoSocket,&TcpSocket::s_error,this,[=](QAbstractSocket::SocketError socketError, TcpSocket* pTcpSocket)
    {
        m_pInfoSocket->clearAll();

        switch (socketError) {
        case QAbstractSocket::RemoteHostClosedError:
            break;
        case QAbstractSocket::HostNotFoundError:
            QMessageBox::information(nullptr, tr("网络错误"),
                                     tr("没有发现服务器"));
            break;
        case QAbstractSocket::ConnectionRefusedError:
            QMessageBox::information(nullptr, tr("网络错误"),
                                     tr("服务器拒绝链接"));
            break;
        case QAbstractSocket::NetworkError:
            QMessageBox::information(nullptr, tr("网络错误"),
                                     tr("网络不可用"));
            break;
        default:
            QMessageBox::information(nullptr, tr("网络错误"),
                                     tr("网络故障:%1(%2)")
                                     .arg(pTcpSocket->errorString()) //为最后一次发生的错误返回一个用户可读的出错信息。
                                     .arg(socketError));
        }

        emit m_pUserInfo->s_loginStatus(-1);
    });

    //连接主机错误
    connect(m_pGameSocket,&TcpSocket::s_error,this,[=](QAbstractSocket::SocketError socketError, TcpSocket* pTcpSocket)
    {
        m_pUserInfo->m_LoginInfo.m_ClientStatus = UserInfo::Client_IsLoginOut;
        m_pGameSocket->clearAll();

        switch (socketError) {
        case QAbstractSocket::RemoteHostClosedError:
            break;
        case QAbstractSocket::HostNotFoundError:
            QMessageBox::information(nullptr, tr("网络错误"),
                                     tr("没有发现服务器"));
            break;
        case QAbstractSocket::ConnectionRefusedError:
            QMessageBox::information(nullptr, tr("网络错误"),
                                     tr("服务器拒绝链接"));
            break;
        case QAbstractSocket::NetworkError:
            QMessageBox::information(nullptr, tr("网络错误"),
                                     tr("网络不可用"));
            break;
        default:
            break;
            /*QMessageBox::information(nullptr, tr("网络错误"),
                                     tr("网络故障:%1(%2)")
                                     .arg(pTcpSocket->errorString() //为最后一次发生的错误返回一个用户可读的出错信息。
                                     .arg(socketError)));
                                     */
        }
        emit s_qml_ChangeAllWindowVisible(2);
        //emit s_ConnectServerErr(10,m_pUserInfo->m_pInfoSocket->error());
    });


    //断开
    connect(m_pInfoSocket,&TcpSocket::s_disconnected,this,[=]()
    {
        m_pInfoSocket->clearAll();
    });

    //断开
    connect(m_pGameSocket,&TcpSocket::s_disconnected,this,[=]()
    {
        m_pUserInfo->m_LoginInfo.m_ClientStatus = UserInfo::Client_IsLoginOut;

        if(m_pGameCore->m_bNetPlay == true && m_pGameCore->isRunning())    //网络游戏时断开
        {
            //m_pGameCore->m_bTerminateGame = true;
            m_pGameCore->TerminateGame(-3, GameCore::Game_Status_Terminated);

            QMessageBox::information(nullptr,"错误","游戏服务器网络断开!");

            emit s_qml_ChangeAllWindowVisible(2);
        }
        else
        {
            //m_pGameCore->m_bTerminateGame = true;
            m_pGameCore->TerminateGame(-3, GameCore::Game_Status_Terminated);

            QMessageBox::information(nullptr,"错误","游戏服务器网络断开!");

            emit s_qml_ChangeAllWindowVisible(2);
        }
        m_pGameSocket->clearAll();
    });


    //InfoSocket数据处理
    connect(m_pInfoSocket,&TcpSocket::s_readyRead,this,&GameManager::OnInfoReadyRead);

    //GameSocket数据处理
    connect(m_pGameSocket,&TcpSocket::s_readyRead,this,&GameManager::OnInfoReadyRead);//OnGameReadyRead



    //游戏发送s_SendDataToServer信号
    connect(m_pGameCore,&Game::s_SendDataToServer,this,[=](QByteArray data, quint8 outControlbyte)
    {
        NetLog(data,false);
        m_pGameCore->m_pGameSocket->send(data, outControlbyte, false);
    });


    //游戏窗口
    connect(m_pGameCore,&GameCore::s_GameOver,this,[=](GameCore::_GameStatus nRet)
    {
        sl_OverGame(nRet);
    });

    connect(m_pGameCore,&GameCore::s_GameInitFinished,this,[=](int playerCount, int myID)
    {
        //qDebug() << "[GameManager]s_GameInitFinished:m_pGameCore->m_bNetPlay:" << m_pGameCore->m_bNetPlay;
        if(m_pGameCore->m_bNetPlay == true)
        {
            m_pGameSocket->sendData(0x10) << static_cast<qint16>(GAME_SERVER_REQUEST)
                                    << static_cast<qint16>(GAME_SERVER_INITOVER)
                                    << m_pUserInfo->m_GameServerUserInfo.unUserGameID;
            m_pGameSocket->send(false);
            //qDebug() << "[GameManager]发送Init!";
        }
    });

    connect(m_pGameCore,&GameCore::s_Message,this,[=](QString msg)
    {

    });
    connect(m_pGameCore,&GameCore::s_Debug,this,[=](QString msg)
    {
        qDebug() << msg;
    });
    connect(m_pGameCore,&GameCore::s_Critical,this,[=](QString msg)
    {
        qCritical() << msg;
    });



//版本检查
    connect(&m_VersionCheck, &VersionCheck::s_JsonParseResult, this, [=]() {

        qDebug() << "[GameManager]VersionCheck:"
                 << m_VersionCheck.m_nForceVersion
                 << m_VersionCheck.m_nLastestVersion
                 << m_VersionCheck.m_strUpdateURL
                 << m_mapGameConfig.value("Version").toInt()
                 << _Game_Version_;

        //如果出错,则强制升级
        if(m_VersionCheck.m_nForceVersion < 0 || m_VersionCheck.m_nLastestVersion < 0)
        {
            emit s_qml_UpdateInfo(m_VersionCheck.m_strUpdateURL, -1);
            return;
        }

        //如果 强制升级 > 目前版本,则强制升级
        if(m_VersionCheck.m_nForceVersion > _Game_Version_)
        {
            emit s_qml_UpdateInfo(m_VersionCheck.m_strUpdateURL, 2);
            return;
        }

        //如果 最新版本 < 目前版本,则出错
        if(m_VersionCheck.m_nLastestVersion < _Game_Version_)
        {
            emit s_qml_UpdateInfo(m_VersionCheck.m_strUpdateURL, -1);
            return;
        }


//安卓还需检测 数据库版本!
#if defined(Q_OS_ANDROID)
        //如果 数据库版本错误,或 数据库版本 < 强制升级版本,则重新复制数据库文件
        if(!m_mapGameConfig.contains("Version")
                || (m_VersionCheck.m_nLastestVersion < m_mapGameConfig.value("Version").toInt())    //版本错误
                || m_VersionCheck.m_nForceVersion > m_mapGameConfig.value("Version").toInt()    //强制更新
                )
        {
            m_pWordLib->close();
            QFile::remove(FIXLOCALPATH_W("English.dat"));
            copyFileAndSetPermissions(FIXLOCALPATH_W("English.dat"), QFileDevice::ReadOwner | QFileDevice::WriteOwner | QFileDevice::ExeOwner);
            if(!LoadDatabase())
            {
                emit s_qml_Message(_T("数据库错误，请重新进入游戏！"), 2);
                return;
            }
        }
#endif

        //如果 最新 > 当前,且最新版本没有被忽略,则建议升级
        if(m_VersionCheck.m_nLastestVersion > _Game_Version_
                && m_VersionCheck.m_nLastestVersion > m_mapGameConfig.value("IgnoreVersion").toInt())
        {
            emit s_qml_UpdateInfo(m_VersionCheck.m_strUpdateURL, 1);
        }
        else
            emit s_qml_UpdateInfo("", 0);


        //显示广播
        if(m_VersionCheck.m_nBroadcastVersion > m_mapGameConfig.value("BroadcastVersion").toInt())
        {
            emit s_qml_Message(m_VersionCheck.m_strBroadcastContent, 0);
            SaveConfigToDb("BroadcastVersion", QString::number(m_VersionCheck.m_nBroadcastVersion));
        }
    });

    connect(&m_VersionCheck, &VersionCheck::s_Critical, this, [=](QString msg) {
        qCritical() << _T("[!GameManager]VersionCheck ERROR:%1").arg(msg);
        emit s_qml_UpdateInfo("https://www.yingyusha.com/wap/user/pcdownload", -1);
    });



//QML
    m_pAppQmlEngine = new QQmlApplicationEngine(this);

    m_pAppQmlEngine->rootContext()->setContextProperty("GameManager",this);
    m_pAppQmlEngine->rootContext()->setContextProperty("GameCore",gameCore());
    m_pAppQmlEngine->rootContext()->setContextProperty("UserInfo",userInfo());
    //m_pAppQmlEngine->rootContext()->setContextProperty("WordLib",m_pWordLib);
    //m_pAppQmlEngine->rootContext()->setContextObject(&gamedata);

    //qDebug() << "!!!!!!";
    //qDebug() << FIXPATH(QMLFiles/Login/login.qml);
    //qDebug() << FIXPATH(QMLFiles/Register/Register.qml);

    //m_pAppQmlEngine->load("file:QMLFiles/game.qml");
    //m_pAppQmlEngine->load(QUrl(QStringLiteral("file:QMLFiles/game.qml")));
//#ifdef QT_NO_DEBUG
    m_pAppQmlEngine->load(FIXRESOURCEURL_R("QMLFiles/game.qml"));
//#else
//    m_pAppQmlEngine->load(FIXLOCALPATH_R("QMLFiles/game.qml"));
//#endif
    //m_pAppQmlEngine->load(FIXPATH(QMLFiles/game.qml));

    //m_pAppQmlEngine->load(FIXPATH(QMLFiles/Login/login.qml));
    //m_pAppQmlEngine->load(FIXPATH(QMLFiles/Register/Register.qml));
    //m_pAppQmlEngine->load(FIXPATH(QMLFiles/GameCenter/GameCenter.qml));
    //m_pAppQmlEngine->load(FIXPATH(QMLFiles/debugWindow.qml));
    //m_pAppQmlEngine->load(QUrl(QStringLiteral("QMLFiles/debugWindow.qml")));

    QList<QObject*> oList = m_pAppQmlEngine->rootObjects();
    if (m_pAppQmlEngine->rootObjects().isEmpty()) {
        qCritical() << "[!GameManager]读取QML文件ERROR!";
        return false;// -1;
    }
    m_pGameWindow = qobject_cast<QQuickWindow*>(oList.at(0));
    //m_pGameWindow = dynamic_cast<QQuickWindow*>(oList.at(0));
    //m_pGameWindow->activateWindow();
    //m_pGameWindow->raise();
/*
    QQuickView *pQuickView = new QQuickView;
    pQuickView->setColor(QColor(Qt::transparent));
    pQuickView->rootContext()->setContextProperty("GameManager",this);
    pQuickView->rootContext()->setContextProperty("GameCore",gameCore());
    pQuickView->rootContext()->setContextProperty("UserInfo",userInfo());
    pQuickView->setSource(QUrl("qrc:/QMLFiles/game.qml"));
    pQuickView->show();
*/
    //pQuickView->setStyleSheet("background:transparent;");
    //pQuickView->setAttribute(Qt::WA_TranslucentBackground);
    //pQuickView->setWindowFlags(Qt::FramelessWindowHint);
    //pQuickView->set

    //pLoginWindow = dynamic_cast<QQuickWindow*>(oList.at(0));
    //pRegisterWindow = dynamic_cast<QQuickWindow*>(oList.at(1));
    //pGameCenterWindow = dynamic_cast<QQuickWindow*>(oList.at(2));
    //pDebugWindow = dynamic_cast<QQuickWindow*>(oList.at(1));

    //pRegisterWindow->hide();
    //pGameCenterWindow->hide();
    //m_pGameWindow->hide();


    //m_pAppQmlEngine->se
    //m_pGameWindow->setColor(QColor(Qt::transparent));
    //m_pGameWindow->setMask(QRegion(QRect(0, 0, 10, 10)));
    //m_pGameWindow->setAttribute(Qt::WA_TranslucentBackground);
    //m_pGameWindow->setStyleSheet("background:transparent;");

    //oList.first()->objectName()



    //pLoginBox->setWindowTitle("登录");
    //pRegister->setWindowTitle("注册");
    //pCenter->setWindowTitle("游戏大厅");
    //m_pGameWindow->setWindowTitle("英语杀");
    //w.setMaximumSize(800,400);
    //w.setMinimumSize(800,400);
    //w.setFixedSize(800,400);
    //w.setWindowFlags(Qt::WindowCloseButtonHint|Qt::WindowFullscreenButtonHint|Qt::WindowMinimizeButtonHint);
    //w.setFixedSize(w.width(),w.height());


    //pLoginBox->show();
    //w.showFullScreen();
    //a.installEventFilter(new EventFilter);








    //单人游戏
    //connect(m_pGameWindow,SIGNAL(s_StartGame(int,int,int,int))
    //        ,this,SLOT(sl_qml_SinglePlay(int,int,int,int)));

    //登录
    //connect(m_pGameWindow,SIGNAL(s_login(QVariant))
    //        ,m_pUserInfo,SLOT(userLogin(QVariant)));

    //注册
    //connect(m_pGameWindow,SIGNAL(s_RegUser(QVariant))
    //        ,m_pUserInfo,SLOT(userReg(QVariant)));

    //选择服务器
    //connect(m_pGameWindow,SIGNAL(s_RegUser(QVariant))
    //        ,m_pUserInfo,SLOT(userReg(QVariant)));




#if defined(Q_OS_WIN32)         //win
    m_pUserInfo->m_LoginInfo.m_nClientType = 1;
#elif defined(Q_OS_ANDROID)     //android
    m_pUserInfo->m_LoginInfo.m_nClientType = 2;
#elif defined(Q_OS_MACOS)
    m_pUserInfo->m_LoginInfo.m_nClientType = 3;
#elif defined(Q_OS_IOS)
    m_pUserInfo->m_LoginInfo.m_nClientType = 4;
#elif defined(Q_OS_LINUX)       //linux,必须在Q_OS_ANDROID之后,因为Android环境会即将Linux也定义
    m_pUserInfo->m_LoginInfo.m_nClientType = 5;
#endif



    QVariant v;
    QMetaObject::invokeMethod(m_pGameWindow,"initOnce"
                              ,Qt::AutoConnection
                              ,Q_RETURN_ARG(QVariant,v)
                              //,Q_ARG(QVariant,0)
                              );


    m_pGameCore->InitOnce();



    m_VersionCheck.m_strJsonURL = "http://update.yingyusha.com/GameInfo.json";
    m_VersionCheck.checkVersion();



    return true;
}





int GameManager::SaveConfigToDb(QString key, QString value)
{
    if(!m_pWordLib->isValid())
        return -1;

    if(m_mapGameConfig.contains(key))
    {
        if(m_mapGameConfig.value(key).toString() == value)
            return 0;

        m_mapGameConfig[key] = value;

        QString sql = QString("UPDATE GameConfig SET Value='%1' WHERE Key='%2'").arg(value).arg(key);
        QSqlQuery query(*m_pWordLib->getDB());  //查询

        if(!query.exec(sql))
        {
            qCritical() << ("[!GameManager]UPDATE GameConfig ERROR!");
            return -2;
        }
        int ret = query.numRowsAffected();
        query.finish();
        qDebug() << "UPDATE numRowsAffected:" << ret << key << m_mapGameConfig[key];
        return ret;
    }
    else
    {
        m_mapGameConfig[key] = value;

        QString sql = QString("INSERT INTO GameConfig(Key,Value) VALUES('%1','%2')").arg(key).arg(value);
        QSqlQuery query(*m_pWordLib->getDB());  //查询

        if(!query.exec(sql))
        {
            qCritical() << "[!GameManager]INSERT GameConfig ERROR!";
            qCritical() << sql;
            return -3;
        }
        int ret = query.numRowsAffected();
        query.finish();
        qDebug() << "INSERT numRowsAffected:" << ret << key << m_mapGameConfig[key];
        return ret;
    }
}

int GameManager::DeleteConfigToDb(QString key)
{
    if(!m_pWordLib->isValid())
        return -1;

    if(m_mapGameConfig.contains(key))
    {
        m_mapGameConfig.remove(key);

        QString sql = QString("DELETE FROM GameConfig WHERE Key='%1'").arg(key);
        QSqlQuery query(*m_pWordLib->getDB());  //查询

        if(!query.exec(sql))
        {
            qCritical() << ("[!GameManager]DELETE GameConfig ERROR!");
            return -2;
        }
        int ret = query.numRowsAffected();
        query.finish();
        qDebug() << "DELETE numRowsAffected:" << ret;
        return ret;
    }
    return 0;
}

int GameManager::LoadConfigFromDb()
{
    if(!m_pWordLib->isValid())
        return -1;

    QString sql = "SELECT * FROM GameConfig";
    QSqlQuery query(*m_pWordLib->getDB());  //查询


    if(!query.exec(sql))
    {
        qCritical() << ("[!GameManager]Query GameConfig ERROR!");
        return -2;
    }

    m_mapGameConfig.clear();
    int ret = query.numRowsAffected();

    while(query.next())
    {
        m_mapGameConfig[query.value("Key").toString()] = query.value("Value");
    }
    query.finish();
    qDebug() << "读取GameConfig结束:"<<m_mapGameConfig.count();
    return ret;
}



bool GameManager::LoadDatabase()
{
    if(!m_pWordLib->connectDB(FIXLOCALPATH_W("English.dat"),"Pleafles@Leamus"))
    {
        QMessageBox::critical(nullptr,"深林孤鹰提示","数据库错误!");
        return false;
    }

    //m_pUserInfo->m_pTempDB = m_pWordLib->getDB();
    if(LoadConfigFromDb() < 0)
    {
        qCritical() << "[!GameManager]LoadConfigFromDb ERROR!:";
        return false;
    }
    return true;
}

int GameManager::CheckConfig()
{
    /*
    if(!m_mapGameConfig.contains("Version"))
    {
        SaveConfigToDb("Version", QString::number(1));
    }

    int version = m_mapGameConfig["Version"].toInt();
    if(version < 8)
    {
#if defined(Q_OS_ANDROID)
        m_pWordLib->close();
        QFile::remove(FIXLOCALPATH_W("English.dat"));
        copyFileAndSetPermissions(FIXLOCALPATH_W("English.dat"), QFileDevice::ReadOwner | QFileDevice::WriteOwner | QFileDevice::ExeOwner);
        return 1;
#endif

    }
    if(version == 8)
    {

    }
    */

    /*
    switch(m_mapGameConfig["Version"].toInt())
    {
        case 1:
            break;
        case 2:
            break;
        default:
            break;
    }*/
    return 0;
}




void GameManager::sl_StartGame(int playerCount,int cID, int lID, int restart, bool netPlay)
{
    emit s_qml_DebugMsg(tr("主线程Manager随机数种子:%1").arg(lmsSrand(-1)));

    m_pUserInfo->setGameStatus(_ClientGameStatus::Game_Playing);
    m_pGameCore->m_bNetPlay = netPlay;
    if(netPlay) //联网游戏
    {

        m_pGameCore->m_bMaster = false;

        m_pGameCore->wordObj.m_pWord = &m_pGameCore->wordObj.m_Word;
        m_pWordLib->init();
        m_pWordLib->m_nType = 1;

    }
    else        //单人游戏
    {

        sl_qml_StartGame();

        m_pGameCore->m_nPlayerCount = playerCount;
        m_pGameCore->m_bMaster = true;
        m_pGameCore->m_nMyID = rand() % playerCount;

        for(int i = 0; i < playerCount; i++)
        {
            m_pGameCore->m_arrayPlayer[i].m_nDuiWu = i;

            if(i == m_pGameCore->m_nMyID)
            {
                m_pGameCore->m_arrayPlayer[i].m_eJiaoSe = _Player::JiaoSe_Self;
                m_pGameCore->m_arrayPlayer[i].m_strName = m_pUserInfo->nickName();
            }
            else
            {
                m_pGameCore->m_arrayPlayer[i].m_eJiaoSe = _Player::JiaoSe_AI;
                m_pGameCore->m_arrayPlayer[i].m_strName = "";
            }
        }


        m_pWordLib->init();
        m_pWordLib->createWords(cID,lID);
        //qDebug() << "!!!cid,lid:" << cID << lID;
        if(restart == 0)
        {
            m_pWordLib->setResult(m_pUserInfo->m_StudyInfo.m_mapClassInfo.value(QString("%1").arg(cID)).value<ClassInfo*>()->m_mapLevel.value(QString::number(lID)).value<LevelInfo*>()->property("wordRecords").toString());
            if(m_pWordLib->unStudiedCount() > 0)  //有没学的
                m_pWordLib->m_nStudyType = 1;
            else
                m_pWordLib->m_nStudyType = 2;      //复习

            m_pWordLib->moveToNextWord();
        }
        else if(restart == 1)        //全部重新开始
        {
            m_pWordLib->m_nStudyType = 1;
            m_pWordLib->setResult("");
            m_pWordLib->moveToNextWord();
        }
        else if(restart == 2)
        {
            m_pWordLib->setResult(m_pUserInfo->m_StudyInfo.m_mapClassInfo.value(QString("%1").arg(cID)).value<ClassInfo*>()->m_mapLevel.value(QString::number(lID)).value<LevelInfo*>()->property("wordRecords").toString());
            if(m_pWordLib->unStudiedCount() > 0)  //有没学的
                m_pWordLib->m_nStudyType = 1;
            else
                m_pWordLib->m_nStudyType = 2;      //复习

            m_pWordLib->moveToNextWord();
        }
        //qDebug() << i<<m_pGameCore->m_nMyID;
    }

    //m_pGameSocket->clearData();
    emit s_StartGame();
    m_pGameCore->start();
    //qDebug() << "游戏开始!!";
}

void GameManager::sl_OverGame(GameCore::_GameStatus nRet)
{
    if(m_pGameCore->m_bNetPlay == true)
    {
        m_pUserInfo->setGameStatus(_ClientGameStatus::Game_Waiting);
        qDebug() << "联网游戏结束！";
        /*
        m_pGameCore->m_pGameSocket->sendData()
                << (qint16)GAME_SERVER_RESPONSE<<(qint16)GAME_SERVER_GAMEOVER;
        m_pGameCore->m_pGameSocket->send();
        */
    }
    else
    {
        //ret = m_pUserInfo->m_StudyInfo.saveResultLocal(m_pWordLib->getDB(),m_pWordLib,m_pUserInfo->m_LoginInfo.id);
        int ret = m_pUserInfo->saveResult(m_pWordLib);
        if(ret)
            qDebug() << "保存单词结果！";
        else
            qDebug() << "未保存单词结果！";
        m_pUserInfo->setGameStatus(_ClientGameStatus::Game_Nothing);
    }

    //非正常退出
    switch(nRet)
    {
    case GameCore::Game_Status_Terminated:
        m_pGameSocket->sendData(0x10) << (qint16)GAME_SERVER_REQUEST
                                << (qint16)GAME_SERVER_GAMEOVER
                                << true;
        m_pGameSocket->send(false);
        m_pUserInfo->m_GameServerUserInfo.nScoreAdd = m_pWordLib->scoreTerminate();
        qDebug() << "[GameManager]强制退出:"<<nRet;
        break;
    case GameCore::Game_Status_GameOver:
        if(m_pGameCore->m_bNetPlay == false)     //单人游戏还得发送游戏结束
        {
            m_pGameSocket->sendData(0x10) << (qint16)GAME_SERVER_REQUEST
                                    << (qint16)GAME_SERVER_GAMEOVER
                                    << false;
            m_pGameSocket->send(false);
        }
        m_pUserInfo->m_GameServerUserInfo.nScoreAdd = m_pWordLib->totalScore() + (m_pGameCore->isWin() ? 10 : 0);
        qDebug() << "[GameManager]正常退出:"<<nRet;
        break;
    case GameCore::Game_Status_Exit:
        m_pUserInfo->m_GameServerUserInfo.nScoreAdd = m_pWordLib->totalScore();
        qDebug() << "[GameManager]指令退出:"<<nRet;
        break;
    default:
        m_pUserInfo->m_GameServerUserInfo.nScoreAdd = m_pWordLib->totalScore();
        qCritical() << "[!GameManager]游戏退出ERROR:"<<nRet;
    }
    /*
    else if(m_pGameCore->m_bMaster == true)
    {
        if(m_pGameCore->m_bNetPlay == true)
        {
            m_pGameCore->m_pGameSocket->sendData()
                    <<(qint16)GAME_DATA
                   <<(qint16)GAME_DATA_GAMEOVER;
            m_pGameCore->m_pGameSocket->send();
        }
    }*/


    //m_pUserInfo->updateGameUserScoreInfoLocal();
    if(m_pUserInfo->m_GameServerUserInfo.nScoreAdd != 0)
    {
        qDebug() << "更新金币";
        m_pUserInfo->updateGameUserScoreInfo();
    }
    else
        qDebug() << "不更新金币";


    emit s_OverGame(nRet);

    //QVariant v;
    //QMetaObject::invokeMethod(m_pGameWindow,"overGame"
    //                          ,Q_RETURN_ARG(QVariant,v)
    //                          ,Q_ARG(QVariant,nRet));
}



void GameManager::sl_qml_CreateGroup(int maxPlayerCount, const QString& password, quint32 classID)
{
    m_pGameSocket->sendData(0x10) << (qint16)GAME_SERVER_REQUEST
                            << (qint16)GAME_SERVER_GROUP_CREATE
                            << (qint16)maxPlayerCount
                            << password
                            << classID;
    m_pGameSocket->send(false);
}

void GameManager::sl_qml_ExitGroup()
{
    m_pGameSocket->sendData(0x10) << (qint16)GAME_SERVER_REQUEST
                            << (qint16)GAME_SERVER_GROUP_EXITGROUP;
    m_pGameSocket->send(false);
}

//gid:0为随机加入;password:密码
void GameManager::sl_qml_JoinGroup(qint32 gid, QString password)
{
    m_pGameSocket->sendData(0x10) << (qint16)GAME_SERVER_REQUEST
                            << (qint16)GAME_SERVER_GROUP_JOINGROUP
                            << gid << password;
    m_pGameSocket->send(false);
}

void GameManager::sl_qml_GetReady(qint16 duiWu)
{
    m_pGameSocket->sendData(0x10) << (qint16)GAME_SERVER_REQUEST
                            << (qint16)GAME_SERVER_GROUP_GETREADY
                            << (qint16)duiWu;
    m_pGameSocket->send(false);
}

void GameManager::sl_qml_StartGame()
{
    m_pGameSocket->sendData(0x10) << (qint16)GAME_SERVER_REQUEST
                            << (qint16)GAME_SERVER_STARTGAME;
    m_pGameSocket->send(false);
}

void GameManager::sl_qml_SendMessage(QString msg, qint16 type)
{
    m_pGameSocket->sendData(0x10) << (qint16)GAME_SERVER_REQUEST
                                << (qint16)GAME_SERVER_GROUP_MESSAGE
                                << (qint16)type
                                << (qint16)m_pGameCore->m_nMyID
                                << msg
                               ;
    m_pGameSocket->send(false);
}


void GameManager::OnInfoReadyRead(TcpSocket* sock)
{
    qint16 data;

    //uint datalen = sock->recievedDataSize();
    //if(m_pGameCore->m_bMaster)
    //    qDebug() << "主机客户端接收数据大小:" << datalen;
    //else
    //    qDebug() << "副机客户端接收数据大小:" << datalen;


    //QDataStream dsData(baData);
    //while(!sock->recievedData().atEnd())
    //if(!sock->recievedData().atEnd())     //不能判断数据是否空,因为有些没有数据,比如8d类型
    {
        switch(sock->m_ucInControlByte)
        {
        case quint8(0x8c):
            qDebug() << "[GameManager]接受到加密Code:" << sock->m_listOutTransfersCode;
            while(!sock->m_listOutCodeData.isEmpty() && !sock->m_listOutTransfersCode.isEmpty())    //如果队列中有数据,则发送
                SendWithCode(sock);
            return;

        default:
            break;
        }   //switch(sock->m_ucInControlByte)


        sock->recievedData() >> data;
        qDebug() << "数据类型1:" << data;
        switch(data)
        {
        case INFO_SERVER_RESPONSE:
            {
                sock->recievedData() >> data;
                switch(data)
                {
                case INFO_SERVER_LOGIN:
                    {
                        sock->recievedData() >> data;
                        switch(data)
                        {
                        case INFO_SERVER_LOGIN_SUCCESS:
                            {
                                sock->recievedData() >> m_pUserInfo->m_LoginInfo.m_unID;
                                sock->recievedData() >> m_pUserInfo->m_LoginInfo.m_unGradeID;

                                m_pUserInfo->m_LoginInfo.m_ClientStatus = UserInfo::Client_IsLoginedGameServer;

                                SaveConfigToDb("LoginUserName",m_pUserInfo->userName());
                                if(true == m_mapGameConfig["rememberPassword"])
                                    SaveConfigToDb("LoginUserPass",m_pUserInfo->m_LoginInfo.m_strPassword);
                                else
                                    SaveConfigToDb("LoginUserPass","");

                                qDebug() << "[InfoServer]登录成功!"<<m_pUserInfo->m_LoginInfo.m_unID<<m_pUserInfo->m_LoginInfo.m_unGradeID;
                                emit m_pUserInfo->s_loginStatus(0);
                                //m_pUserInfo->loadGameServersInfo();
                            }
                            break;
                        case INFO_SERVER_LOGIN_FAIL:
                            {
                                sock->recievedData() >> data;
                                //m_pUserInfo->m_LoginInfo.m_ClientStatus = UserInfo::Client_IsLoginOut;
                                switch(data)
                                {
                                case -1:
                                    //QMessageBox::information(pLoginBox,tr("登录失败"),tr("用户名或密码错误"));
                                    break;
                                case -2:
                                    //QMessageBox::information(pLoginBox,tr("登录失败"),tr("已经在其他地方登录"));
                                    break;
                                default:
                                    //QMessageBox::information(pLoginBox,tr("登录失败"),tr("未知错误"));
                                    break;
                                }
                                emit m_pUserInfo->s_loginStatus(data);

                                //pLoginBox->setStatus(0);
                            }
                            break;
                        }
                    }
                    break;
                case INFO_SERVER_REGISTER:
                    {
                        sock->recievedData() >> data;
                        switch(data)
                        {
                        case INFO_SERVER_REGISTER_SUCCESS:
                            {
                                m_pUserInfo->m_LoginInfo.m_ClientStatus = UserInfo::Client_IsLoginedGameServer;
                                emit m_pUserInfo->s_regStatus(0);
                                //QMessageBox::information(pRegister,tr("注册成功"),tr("注册成功"));
                                //pRegister->hide();
                                //pCenter->show();
                            }
                            break;
                        case INFO_SERVER_REGISTER_FAIL:
                            {
                                sock->recievedData() >> data;
                                //m_pUserInfo->m_LoginInfo.m_ClientStatus = UserInfo::Client_IsLoginedInfoServer;
                                //if(data == 1)
                                    emit m_pUserInfo->s_regStatus(data);
                                //QMessageBox::information(pRegister,tr("注册失败"),tr("注册失败"));
                                //pRegister->setStatus(0);
                            }
                            break;
                        }
                    }
                    break;

                case INFO_SERVER_SERVERINFO:
                    {
                        sock->recievedData() >> data;
                        switch(data)
                        {
                        case INFO_SERVER_SERVERINFO_SUCCESS:
                            {
                                m_pUserInfo->clearGameServersInfo();
                                sock->recievedData() >> data;
                                qDebug() << "[InfoServer]获取游戏服务器列表成功:" << data;
                                while(data)
                                {
                                    _GameServerInfo *pGameServerInfo = new _GameServerInfo;
                                    sock->recievedData() >> pGameServerInfo->m_unServerID;
                                    sock->recievedData() >> pGameServerInfo->m_strName;
                                    sock->recievedData() >> pGameServerInfo->m_strIP;
                                    sock->recievedData() >> pGameServerInfo->m_unPort;
                                    sock->recievedData() >> pGameServerInfo->m_strKey;
                                    m_pUserInfo->m_mapGameServerInfo.insert(QString::number(pGameServerInfo->m_unServerID)
                                                                          , QVariant::fromValue(pGameServerInfo));
                                    //m_GameServerInfoList.append(QVariant::fromValue<_GameServerInfo*>(pGameInfo));
                                    //m_GameServerInfoList.insert(query.value("ID").toString(),QVariant::fromValue<ClassInfo*>(cInfo));
                                    data--;
                                }
                                m_pInfoSocket->close();
                            }
                            break;
                        case INFO_SERVER_SERVERINFO_FAIL:
                            {
                                qCritical() << "[!InfoServer]获取游戏服务器信息ERROR！";
                                m_pInfoSocket->close();
                            }
                            break;
                        }
                    }
                    break;

                default:
                    //m_pGameWindow->scene->ShowDebug(tr("GAME_SERVER通信错误"));
                    break;
                }
            }
            break;

        case GAME_SERVER_RESPONSE:
            {
                sock->recievedData() >> data;
                switch(data)
                {
                case GAME_SERVER_REGISTERGAMEUSERINFO:
                    {
                        sock->recievedData() >> data;
                        switch(data)
                        {
                        case GAME_SERVER_REGISTERGAMEUSERINFO_SUCCESS:
                            {
                                sock->recievedData() >> m_pUserInfo->m_GameServerUserInfo.unUserGameID;

                                m_pUserInfo->setFlagCorrectAnswer(false);
                                m_pUserInfo->setCanReview(false);

                                m_pUserInfo->loadClassInfo();
                                qDebug() << "[GameManager]注册游戏用户信息成功:" << m_pUserInfo->m_GameServerUserInfo.unUserGameID;

                                m_pUserInfo->m_LoginInfo.m_ClientStatus = UserInfo::Client_IsLoginedGameServer;
                                emit m_pUserInfo->s_choiceGameServerStatus(0);
                            }
                        break;
                        case GAME_SERVER_REGISTERGAMEUSERINFO_FAIL:
                            {
                                sock->recievedData() >> data;
                                switch(data)
                                {
                                case 1:
                                    emit m_pUserInfo->s_regGameStatus(1);
                                    break;
                                default:
                                    qCritical() << "[!GameManager]获取游戏用户信息ERROR:" << data;
                                }

                            }
                        break;
                        default:
                            m_pUserInfo->s_regGameStatus(-1);
                        }
                    }
                break;

                case GAME_SERVER_GAMEUSERINFO:
                    {
                        sock->recievedData() >> data;
                        switch(data)
                        {
                        case GAME_SERVER_GAMEUSERINFO_SUCCESS:
                            {
                                quint32 userGameID;
                                QString nick;
                                qint32 score;
                                qint16 sex;
                                sock->recievedData() >> userGameID;
                                sock->recievedData() >> nick;
                                sock->recievedData() >> sex;
                                sock->recievedData() >> score;

                                sock->recievedData() >> m_pUserInfo->m_GameServerUserInfo.nScoreYesterday;
                                sock->recievedData() >> m_pUserInfo->m_GameServerUserInfo.nScoreWeek;

                                m_pUserInfo->m_GameServerUserInfo.unUserGameID = userGameID;
                                m_pUserInfo->setNickName(nick);
                                m_pUserInfo->setSex(sex);
                                m_pUserInfo->setScoreCount(score);

                                qDebug() << "[GameManager]获取游戏用户信息成功";

                                //!!!???鹰：这里需要改（读取）
                                m_pUserInfo->setFlagCorrectAnswer(false);
                                m_pUserInfo->setCanReview(false);

                                m_pUserInfo->loadClassInfo();

                                m_pUserInfo->m_LoginInfo.m_ClientStatus = UserInfo::Client_IsLoginedGameServer;

                                emit m_pUserInfo->s_choiceGameServerStatus(0);

                                if(userGameID <= 0)
                                    qCritical() << ("[!GameManager]获取GameUserID ERROR:" + QString::number(userGameID));
                            }
                            break;
                        case GAME_SERVER_GAMEUSERINFO_FAIL:
                            {
                                sock->recievedData() >> data;
                                switch(data)
                                {
                                case 1: //需要注册
                                    emit m_pUserInfo->s_choiceGameServerStatus(1);
                                    break;
                                default:
                                    qCritical() << "[!GameManager]获取游戏用户信息ERROR:" << data;
                                }

                            }
                            break;
                        default:
                            emit m_pUserInfo->s_choiceGameServerStatus(-1);
                        }
                    }
                    break;
                case GAME_SERVER_CLASSINFO:
                    {
                        sock->recievedData() >> data;
                        switch(data)
                        {
                        case GAME_SERVER_CLASSINFO_SUCCESS:
                            {
                                m_pUserInfo->m_StudyInfo.clearClassInfo();
                                sock->recievedData() >> data;
                                qDebug() << "[GameManager]获取ClassInfo列表成功:" << data;
                                while(data)
                                {

                                    ClassInfo *cInfo = new ClassInfo;
                                    sock->recievedData() >> cInfo->m_nClassID;
                                    sock->recievedData() >> cInfo->m_unClassLevelCount;
                                    sock->recievedData() >> cInfo->m_strClassName;
                                    m_pUserInfo->m_StudyInfo.m_mapClassInfo.insert(QString("%1").arg(cInfo->m_nClassID),QVariant::fromValue<ClassInfo*>(cInfo));
                                    qDebug() << "ClassID:" << cInfo->m_nClassID << ":" << cInfo->m_strClassName;

                                    data--;
                                }
                                qDebug() << "1.共" << m_pUserInfo->m_StudyInfo.m_mapClassInfo.count();
                                qDebug() << "------------------";

                                m_pUserInfo->loadStudyInfo();
                                m_pUserInfo->loadItemsInfo();
                                m_pUserInfo->loadRankingInfo();

                            }
                            break;
                        case GAME_SERVER_CLASSINFO_FAIL:
                            {
                                sock->recievedData() >> data;
                                qCritical() << "[!GameManager]获取ClassInfo列表ERROR:" << data;
                            }
                            break;
                        }
                    }
                    break;
                case GAME_SERVER_STUDYINFO:
                    {
                        sock->recievedData() >> data;
                        switch(data)
                        {
                        case GAME_SERVER_STUDYINFO_SUCCESS:
                            {
                                quint32 recordCount;
                                sock->recievedData() >> recordCount;
                                qDebug() << "[GameManager]获取StudyInfo列表成功:" << recordCount;
                                while(recordCount != 0)
                                {
                                    LevelInfo *pLevel = new LevelInfo;
                                    sock->recievedData() >> pLevel->m_nClassID;
                                    sock->recievedData() >> pLevel->m_nLevelID;
                                    //sock->recievedData() >> pLevel->m_unWordCount;
                                    sock->recievedData() >> pLevel->m_strWordRecords;

                                    pLevel->m_unWordCount = m_pWordLib->getWordCount(pLevel->m_nClassID, pLevel->m_nLevelID);

                                    //存放在classInfoMap下
                                    if(m_pUserInfo->m_StudyInfo.m_mapClassInfo.contains(QString("%1").arg(pLevel->m_nClassID)))
                                    {
                                        m_pUserInfo->m_StudyInfo.m_mapClassInfo.value(QString("%1").arg(pLevel->m_nClassID)).value<ClassInfo*>()->m_mapLevel.insert(QString::number(pLevel->m_nLevelID), QVariant::fromValue(pLevel));
                                    }
                                    else
                                    {
                                        qCritical() << "[!GameManager]不存在ClassID的levelInfo:" << pLevel->m_nClassID;
                                        delete pLevel;
                                        pLevel = nullptr;
                                    }
                                    recordCount--;
                                }
                                qDebug() << "2.ClassInfoMap共:" << m_pUserInfo->m_StudyInfo.m_mapClassInfo.count();
                                qDebug() << "2.m_mapLevel:" << m_pUserInfo->m_StudyInfo.m_mapClassInfo.value("1").value<ClassInfo*>()->m_mapLevel.count();
                                qDebug() << "------------------";
                            }
                            break;
                        case GAME_SERVER_STUDYINFO_FAIL:
                            {
                                sock->recievedData() >> data;
                                qCritical() << "[!GameManager]获取StudyInfo列表ERROR:" << data;
                            }
                            break;
                        }
                    }
                    break;
                case GAME_SERVER_SAVESTUDYINFO:
                    {
                        sock->recievedData() >> data;
                        switch(data)
                        {
                        case GAME_SERVER_SAVESTUDYINFO_SUCCESS:
                            {
                                sock->recievedData() >> data;
                                qDebug() << "[GameManager]保存学习信息成功";
                                qDebug() << "------------------";

                                if(data == 1)       //新增一关
                                {
                                    quint32 classID;
                                    quint32 levelID;
                                    sock->recievedData() >> classID >> levelID;
                                    /*
                                    LevelInfo *pLevel = new LevelInfo;
                                    pLevel->m_nClassID = classID;
                                    pLevel->m_nLevelID = levelID;
                                    pLevel->m_unWordCount = m_pWordLib->getWordCount(classID, levelID);
                                    //pLevel->m_CorrectCount = query.value("CorrectCount").toInt();
                                    //pLevel->m_MistakeCount = query.value("MistakeCount").toInt();
                                    pLevel->m_strWordRecords = m_pWordLib->result;   //!!!注意这里
                                    m_pUserInfo->m_StudyInfo.m_mapClassInfo.value(QString::number(m_pWordLib->m_nClassID)).value<ClassInfo*>()->m_mapLevel.insert(QString::number(pLevel->m_nLevelID), QVariant::fromValue(pLevel));
                                    */
                                    //emit s_RefreshAllLevels();
                                    qDebug() << "[GameManager]INSERT" << m_pUserInfo->m_StudyInfo.m_mapClassInfo.value(QString::number(m_pWordLib->m_nClassID)).value<ClassInfo*>()->classID();
                                }
                                else if(data == 0)  //修改原关
                                {
                                    //((LevelInfo*)(m_pUserInfo->m_StudyInfo.m_mapClassInfo.value(QString("%1").arg(m_pWordLib->m_nClassID)).value<ClassInfo*>()->m_mapLevel.value(QString(m_pWordLib->m_nLevelID))))->m_strWordRecords = m_pWordLib->result;

                                    /*
                                    m_pUserInfo->m_StudyInfo.m_mapClassInfo.value(QString::number(m_pWordLib->m_nClassID)).value<ClassInfo*>()->m_mapLevel.value(QString::number(m_pWordLib->m_nLevelID)).value<LevelInfo*>()->m_strWordRecords = m_pWordLib->result;
                                    */
                                    //emit s_RefreshAllLevels();
                                    qDebug() << "[GameManager]UPDATE"<<m_pUserInfo->m_StudyInfo.m_mapClassInfo.value(QString::number(m_pWordLib->m_nClassID)).value<ClassInfo*>()->classID();
                                }
                                else
                                    qCritical() << "[!GameManager]保存学习信息ERROR!";
                            }
                            break;
                        case GAME_SERVER_SAVESTUDYINFO_FAIL:
                            {
                                sock->recievedData() >> data;
                                qCritical() << "[!GameManager]保存学习信息ERROR:" << data;
                            }
                            break;
                        }
                    }
                    break;
                case GAME_SERVER_UPDATESCORE:
                    {
                        sock->recievedData() >> data;
                        switch(data)
                        {
                        case GAME_SERVER_UPDATESCORE_SUCCESS:
                            {
                                qDebug() << "[GameManager]保存学习信息成功";
                                qDebug() << "------------------";

                                m_pUserInfo->updateScoreCount();
                            }
                            break;
                        case GAME_SERVER_UPDATESCORE_FAIL:
                            {
                                sock->recievedData() >> data;
                                qCritical() << "[!GameManager]保存学习信息ERROR:" << data;
                            }
                            break;
                        }
                    }
                    break;

                case GAME_SERVER_RANKING:
                    {
                        sock->recievedData() >> data;
                        switch(data)
                        {
                        case GAME_SERVER_RANKING_SUCCESS:
                            {
                                m_pUserInfo->m_RankingInfo.clearRankingInfo();
                                sock->recievedData() >> data;
                                qDebug() << "[GameManager]获取Ranking成功:" << data;
                                while(data > 0)
                                {

                                    PerUserGameRankingInfo *perInfo = new PerUserGameRankingInfo;
                                    sock->recievedData() >> perInfo->m_unUserGameID;
                                    sock->recievedData() >> perInfo->m_nType;
                                    sock->recievedData() >> perInfo->m_strNickName;
                                    sock->recievedData() >> perInfo->m_nScoreTotal;
                                    sock->recievedData() >> perInfo->m_nScore;
                                    if(!m_pUserInfo->m_RankingInfo.m_mapUserGameRankingInfoList.contains(perInfo->m_nType))
                                        m_pUserInfo->m_RankingInfo.m_mapUserGameRankingInfoList.insert(perInfo->m_nType, new QObjectList);
                                    m_pUserInfo->m_RankingInfo.m_mapUserGameRankingInfoList.value(perInfo->m_nType)->append(perInfo);

                                    data--;
                                }
                                qDebug() << "共:" << m_pUserInfo->m_RankingInfo.m_mapUserGameRankingInfoList.count();
                                qDebug() << "------------------";

                                emit m_pUserInfo->s_RefreshRanking(0);
                            }
                            break;
                        case GAME_SERVER_RANKING_FAIL:
                            {
                                sock->recievedData() >> data;
                                qCritical() << "[!GameManager]获取RankingERROR:" << data;
                                emit m_pUserInfo->s_RefreshRanking(data);
                            }
                            break;
                        }
                    }
                    break;

                case GAME_SERVER_ITEMS:
                    {
                        sock->recievedData() >> data;
                        switch(data)
                        {
                        case GAME_SERVER_ITEMS_SUCCESS:
                            {
                                m_pUserInfo->m_GameServerUserInfo.m_ItemsInfo.clearItemsInfo();

                                sock->recievedData() >> data;
                                qDebug() << "[GameManager]获取Items成功:" << data;
                                while(data > 0)
                                {

                                    PerItemInfo *perInfo = new PerItemInfo;
                                    sock->recievedData() >> perInfo->m_unID;
                                    sock->recievedData() >> perInfo->m_nType;
                                    sock->recievedData() >> perInfo->m_nValue;
                                    sock->recievedData() >> perInfo->m_nStatus;
                                    sock->recievedData() >> perInfo->m_dtAddDateTime;
                                    sock->recievedData() >> perInfo->m_dtRequireDateTime;
                                    m_pUserInfo->m_GameServerUserInfo.m_ItemsInfo.m_listItems.append(perInfo);

                                    data--;
                                }
                                qDebug() << "共:"<<m_pUserInfo->m_GameServerUserInfo.m_ItemsInfo.m_listItems.count();
                                qDebug() << "------------------";

                                m_pUserInfo->refreshItems();

                                emit m_pUserInfo->s_RefreshItems(0);
                            }
                            break;
                        case GAME_SERVER_ITEMS_FAIL:
                            {
                                sock->recievedData() >> data;
                                qCritical() << "[!GameManager]获取Items ERROR:" << data;
                                emit m_pUserInfo->s_RefreshItems(data);
                            }
                            break;
                        }
                    }
                    break;



                //群操作
                case GAME_SERVER_GROUP_CREATE:
                    {
                        sock->recievedData() >> data;
                        switch(data)
                        {
                        case GAME_SERVER_GROUP_CREATE_SUCCESS:
                            {
                                m_pUserInfo->setGameStatus(_ClientGameStatus::Game_Waiting);
                                sock->recievedData() >> m_pUserInfo->m_GameInfo.m_nGroupId;
                                emit s_qml_JoinGroup(m_pUserInfo->m_GameInfo.m_nGroupId);
                                qDebug() << "[GameManager]创建房间成功:" << m_pUserInfo->m_GameInfo.m_nGroupId;
                            }
                            break;
                        case GAME_SERVER_GROUP_CREATE_FAIL:
                            {
                                sock->recievedData() >> data;
                                qCritical() << "[!GameManager]创建房间ERROR:" << data;
                            }
                            break;
                        }
                    }
                    break;

                case GAME_SERVER_GROUP_CLOSE:
                    {
                    }
                    break;
                case GAME_SERVER_GROUP_UPDATE:
                    {
                    }
                    break;
                case GAME_SERVER_GROUP_SENDALLGROUPINFOS:
                    {
                    }
                    break;


                case GAME_SERVER_GROUP_JOINGROUP:
                    {
                        sock->recievedData() >> data;
                        switch(data)
                        {
                        case GAME_SERVER_GROUP_JOINGROUP_SUCCESS:
                            {
                                sock->recievedData() >> m_pUserInfo->m_GameInfo.m_nGroupId;
                                m_pUserInfo->setGameStatus(_ClientGameStatus::Game_Waiting);
                                emit s_qml_JoinGroup(m_pUserInfo->m_GameInfo.m_nGroupId);
                                //QMessageBox::information(pRegister,tr("加入房间"),tr("加入成功"));
                                //pCenter->setStatus(1);
                            }
                            break;
                        case GAME_SERVER_GROUP_JOINGROUP_FAIL:
                            {
                                sock->recievedData() >> data;
                                switch(data)
                                {
                                case -1:
                                    //QMessageBox::information(pLoginBox,tr("加入房间失败"),tr("您已经加入了某个房间,请先退出"));
                                    break;
                                case -2:
                                    //QMessageBox::information(pLoginBox,tr("加入房间失败"),tr("所有房间已满"));
                                    m_pUserInfo->setGameStatus(_ClientGameStatus::Game_Nothing);
                                    break;
                                case -3:
                                    //QMessageBox::information(pLoginBox,tr("加入房间失败"),tr("没有此房间"));
                                    m_pUserInfo->setGameStatus(_ClientGameStatus::Game_Nothing);
                                    break;
                                case -4:
                                    //QMessageBox::information(pLoginBox,tr("加入房间失败"),tr("此房间正在游戏中"));
                                    m_pUserInfo->setGameStatus(_ClientGameStatus::Game_Nothing);
                                    break;
                                default:
                                    //QMessageBox::information(pLoginBox,tr("加入房间失败"),tr("未知错误"));
                                    m_pUserInfo->setGameStatus(_ClientGameStatus::Game_Nothing);
                                    break;
                                }
                                //pCenter->setStatus(0);
                            }
                            break;
                        }
                    }
                    break;

                case GAME_SERVER_GROUP_OTHERSINFO:
                    {
                        sock->recievedData() >> data;
                        switch(data)
                        {
                        case GAME_SERVER_GROUP_OTHERSINFO_JOINGROUP:
                            {
                                QString nickName;
                                bool bIn;
                                sock->recievedData() >> nickName >> bIn;
                                emit s_qml_OthersJoinGroup(nickName, bIn);
                            }
                            break;
                        case GAME_SERVER_GROUP_OTHERSINFO_READY:
                            {
                                QString nickName;
                                qint16 status;
                                qint16 duiWu;
                                sock->recievedData() >> nickName >> status >> duiWu;
                                emit s_qml_OthersReadyInGroup(nickName, status, duiWu);
                            }
                            break;

                        case GAME_SERVER_GROUP_OTHERSINFO_MESSAGE:
                            {
                                qint16 type;
                                qint16 seatID;
                                QString message;
                                sock->recievedData() >> type >> seatID >> message;
                                emit s_qml_OthersMessage(type, seatID, message);
                            }
                            break;
                        default:
                            qCritical() << ("[!GameManager]GAME_SERVER_GROUP_OTHERSINFO ERROR!");
                            break;
                        }

                    }
                    break;
                case GAME_SERVER_GROUP_EXITGROUP:
                    {
                        sock->recievedData() >> data;
                        switch(data)
                        {
                        case GAME_SERVER_GROUP_EXITGROUP_SUCCESS:
                            {
                                m_pUserInfo->m_GameInfo.m_nGroupId = -1;
                                m_pUserInfo->setGameStatus(_ClientGameStatus::Game_Nothing);
                                qDebug() << "[GameManager]退出房间成功:";
                                //QMessageBox::information(pRegister,tr("退出房间"),tr("成功"));
                                //pCenter->setStatus(0);
                            }
                            break;
                        case GAME_SERVER_GROUP_EXITGROUP_FAIL:
                            {
                                sock->recievedData() >> data;
                                qCritical() << "[!GameManager]退出房间 ERROR:" << data;
                                //QMessageBox::information(pRegister,tr("退出房间"),tr("失败"));
                            }
                            break;
                        }
                    }
                    break;

                case GAME_SERVER_GROUP_GETREADY:
                    {
                        sock->recievedData() >> data;
                        switch(data)
                        {
                        case GAME_SERVER_GROUP_GETREADY_SUCCESS:
                            {
                                sock->recievedData() >> data;
                                m_pUserInfo->setGameStatus((_ClientGameStatus)data);
                                qDebug() << "[GameManager]切换状态成功:" << (_ClientGameStatus)data;
                                //QMessageBox::information(pRegister,tr("退出房间"),tr("成功"));
                                //pCenter->setStatus(0);
                            }
                            break;
                        case GAME_SERVER_GROUP_GETREADY_FAIL:
                            {
                                sock->recievedData() >> data;
                                qCritical() << "[!GameManager]切换状态 ERROR:" << (_ClientGameStatus)data;
                                //QMessageBox::information(pRegister,tr("退出房间"),tr("失败"));
                            }
                            break;
                        }
                    }
                    break;

                case GAME_SERVER_STARTGAME:
                    {
                        sock->recievedData() >> data;
                        switch(data)
                        {
                        case GAME_SERVER_STARTGAME_SUCCESS:
                            {
                                qDebug() << "[GameManager]开始游戏成功!";
                                //QMessageBox::information(pRegister,tr("退出房间"),tr("成功"));
                                //pCenter->setStatus(0);


                                //传递所有武将信息！！！
                                sock->recievedData() >> data;
                                m_pGameCore->m_nPlayerCount = data;

                                //QVector<quint32> playerGameIDArray;
                                //QVector<qint16> playerDuiWuArray;
                                //QList<qint32> playerJiaoSeList;

                                //sock->recievedData() >> playerGameIDArray >> playerDuiWuArray;
                                //sock->recievedData() >> playerJiaoSeList;

                                //设置所有角色的m_eJiaoSe!
                                int i = 0;
                                for(i = 0; i < m_pGameCore->m_nPlayerCount; i++)
                                {
                                    qint16 index;       //在服务器上的号(非index)
                                    quint32 gameID;
                                    qint16 duiwu;
                                    sock->recievedData() >> index;  //没用
                                    sock->recievedData() >> gameID;
                                    sock->recievedData() >> m_pGameCore->m_arrayPlayer[i].m_strName;
                                    sock->recievedData() >> duiwu;

                                    m_pGameCore->m_arrayPlayer[i].m_nDuiWu = duiwu;

                                    //如果是本人
                                    if(gameID == m_pUserInfo->m_GameServerUserInfo.unUserGameID)
                                    {
                                        m_pGameCore->m_nMyID = i;
                                        m_pGameCore->m_arrayPlayer[i].m_eJiaoSe = _Player::JiaoSe_Self;
                                    }
                                    /*else if(playerGameIDArray.at(i) == -1)
                                    {
                                        m_pGameCore->m_arrayPlayer[i].m_eJiaoSe = _Player::JiaoSe_Self;
                                    }*/
                                    else if(gameID == 0)   //电脑
                                        m_pGameCore->m_arrayPlayer[i].m_eJiaoSe = _Player::JiaoSe_AI;
                                    else            //其他网络玩家
                                        m_pGameCore->m_arrayPlayer[i].m_eJiaoSe = _Player::JiaoSe_Others;

                                        //m_pGameCore->m_arrayPlayer[i].m_eJiaoSe = (_Player::JiaoSe)playerJiaoSeList[i];
                                }
                                /*
                                QList<qint16>::iterator ii;
                                for (ii = playerTypeList.begin(); ii != playerTypeList.end(); ++ii)
                                {
                                       m_pGameCore->m_arrayPlayer[i].iJiaoSe = *ii;
                                }*/

                                qDebug() << "StartGame:" << m_pGameCore->m_nMyID << m_pGameCore->m_nPlayerCount << m_pGameCore->m_bMaster;

                                sl_StartGame(m_pGameCore->m_nPlayerCount,1,1,0,true);
                            }
                            break;
                        case GAME_SERVER_STARTGAME_FAIL:
                            {
                                sock->recievedData() >> data;
                                qCritical() << "[!GameManager]开始游戏 ERROR:" << data;
                                //QMessageBox::information(pRegister,tr("退出房间"),tr("失败"));
                            }
                            break;
                        }
                    }
                    break;


                case GAME_SERVER_GAMEOVER:
                    {
                        sock->recievedData() >> data;
                        qDebug() << "[GameManager]服务器游戏逻辑结束:" << data;
                        m_pGameCore->TerminateGame(data);
                    }
                    break;

                default:
                    qCritical() << "[!GameManager]数据 ERROR 2:" << data;
                    break;
                }

            }
            break;


        case GAME_DATA:
            {
                if(m_pGameCore->gameStatus() != GameCore::Game_Status_Continue)
                {
                    qCritical() << (_T("[!GameManager]Warning!接收GAME包时游戏已经结束:%1").arg(m_pGameCore->gameStatus()));
                    return;
                }


                sock->recievedData() >> data;
                qDebug() << "数据GAME_DATA类型2:" << data;
                switch(data)
                {
                case GAME_DATA_TRANSFER_ALLWUJIANGCHOICED:
                    {
                        qDebug() << "武将选择接收处理中:";
                        _GameData *pData = new _GameData;
                        if(pData == nullptr)
                        {
                            m_pGameCore->TerminateGame(-10, GameCore::Game_Status_ERROR);
                            return;
                        }

                        pData->type = data;

                        //循环设置武将
                        sock->recievedData() >> pData->ChoiceWuJiangData.nPlayerCount
                                             >> pData->ChoiceWuJiangData.nWuJiangCount;
                        qDebug() << "nPlayerCount:" << pData->ChoiceWuJiangData.nPlayerCount << "nWuJiangCount" << pData->ChoiceWuJiangData.nWuJiangCount;

                        int i, j;
                        for(i = 0; i < pData->ChoiceWuJiangData.nPlayerCount; i++)
                        {

                            for(j = 0; j < pData->ChoiceWuJiangData.nWuJiangCount; j++)
                            {
                                qint16 wuJiangID;
                                sock->recievedData() >> wuJiangID;
                                qDebug() << "wuJiangID:" << j << ":" << wuJiangID;
                                if(i != m_pGameCore->m_nMyID)
                                {
                                    m_pGameCore->m_mapWuJiangUsingTimes[wuJiangID] ++;
                                    m_pGameCore->m_arrayPlayer[i].getWuJiang((_WuJiang::_Value)wuJiangID, j);
                                }
                            }
                        }

                        if(!pData->CheckGameData())
                        {
                            if(pData != nullptr)delete pData;
                            m_pGameCore->TerminateGame(-11, GameCore::Game_Status_ERROR);
                            return;
                        }
                        m_pGameCore->m_Producer.safeIn(pData);
                        qDebug() << "武将选择数接收处理完毕:";
                    }
                    break;
                case GAME_DATA_TRANSFER_XIPAI:
                    {
                        //qDebug() << "接收到转发数据类型:" << data;
                        qDebug() << "洗牌接收处理中:";
                        _GameData *pData = new _GameData;
                        if(pData == nullptr)
                        {
                            m_pGameCore->TerminateGame(-20, GameCore::Game_Status_ERROR);
                            return;
                        }

                        pData->type = data;

                        sock->recievedData() >> pData->XiPaiData.nData;
                        sock->recievedData() >> pData->XiPaiData.nDataLength;

                        if(!pData->CheckGameData())
                        {
                            if(pData != nullptr)delete pData;
                            m_pGameCore->TerminateGame(-21, GameCore::Game_Status_ERROR);
                            return;
                        }


                        pData->XiPaiData.pData = new char[pData->XiPaiData.nDataLength];
                        if(pData->XiPaiData.pData == nullptr)
                        {
                            delete pData;
                            m_pGameCore->TerminateGame(-22, GameCore::Game_Status_ERROR);
                            return;
                        }
                        int ret = sock->recievedData().readRawData(pData->XiPaiData.pData,pData->XiPaiData.nDataLength);
                        if(ret != pData->XiPaiData.nDataLength)
                        {
                            emit s_qml_DebugMsg(tr("读取数据出错:%1").arg(ret));
                            delete pData->XiPaiData.pData;
                            delete pData;
                            m_pGameCore->TerminateGame(-23, GameCore::Game_Status_ERROR);
                            return;
                        }

                        m_pGameCore->m_Producer.safeIn(pData);
                        qDebug() << "洗牌接收处理完毕:";
                    }
                    break;
                case GAME_DATA_TRANSFER_CHUPAI:
                    {
                        qDebug() << "出牌接收处理中:";
                        //qDebug() << "接收到转发数据类型:" << data;
                        _GameData *pData;
                        pData = new _GameData;
                        if(pData == nullptr)
                        {
                            m_pGameCore->TerminateGame(-30, GameCore::Game_Status_ERROR);
                            return;
                        }

                        pData->type = data;

                        sock->recievedData() >> pData->ChuPaiData.nData;
                        sock->recievedData() >> pData->ChuPaiData.nDataLength;

                        if(!pData->CheckGameData())
                        {
                            if(pData != nullptr)delete pData;
                            m_pGameCore->TerminateGame(-31, GameCore::Game_Status_ERROR);
                            return;
                        }


                        pData->ChuPaiData.pData = new char[pData->ChuPaiData.nDataLength];
                        if(pData->ChuPaiData.pData == nullptr)
                        {
                            delete pData;
                            m_pGameCore->TerminateGame(-32, GameCore::Game_Status_ERROR);
                            return;
                        }
                        int ret = sock->recievedData().readRawData(pData->ChuPaiData.pData,pData->ChuPaiData.nDataLength);
                        if(ret != pData->ChuPaiData.nDataLength)
                        {
                            emit s_qml_DebugMsg(tr("读取数据出错:%1").arg(ret));
                            delete pData->ChuPaiData.pData;
                            delete pData;
                            m_pGameCore->TerminateGame(-33, GameCore::Game_Status_ERROR);
                            return;
                        }

                        m_pGameCore->m_Producer.safeIn(pData);
                        //qDebug() << "接收处理完毕:" << data;
                        qDebug() << "出牌接收处理完毕:";
                    }
                    break;
                case GAME_DATA_TRANSFER_WENTI:
                    {
                        qDebug() << "问题接收处理中:"<<sock->recievedData().device()->pos();
                        _GameData *pData;
                        pData = new _GameData;
                        if(pData == nullptr)
                        {
                            m_pGameCore->TerminateGame(-40, GameCore::Game_Status_ERROR);
                            return;
                        }

                        pData->type = data;

                        //pData->WenTiData = new _EnglishWord;
                        sock->recievedData() >> pData->WenTiData.arrayID[0]
                                             >> pData->WenTiData.arrayID[1]
                                             >> pData->WenTiData.arrayID[2]
                                             >> pData->WenTiData.arrayID[3]
                                             >> pData->WenTiData.nAnswer;


                        if(!pData->CheckGameData())
                        {
                            if(pData != nullptr)delete pData;
                            m_pGameCore->TerminateGame(-41, GameCore::Game_Status_ERROR);
                            return;
                        }
                        m_pGameCore->m_Producer.safeIn(pData);
                        qDebug() << "问题接收处理完毕!";
                        //<< sock->recievedData().device()->pos()
                        //       <<sock->recievedData().device()->atEnd()
                        //      <<sock->recievedData().device()->size();
                    }
                    break;
                case GAME_DATA_TRANSFER_ANSWER:
                    {
                        qDebug() << "回答接收处理中:";
                        _GameData *pData;
                        pData = new _GameData;
                        if(pData == nullptr)
                        {
                            m_pGameCore->TerminateGame(-50, GameCore::Game_Status_ERROR);
                            return;
                        }

                        pData->type = data;

                        sock->recievedData() >> pData->nAnswer;

                        if(!pData->CheckGameData())
                        {
                            if(pData != nullptr)delete pData;
                            m_pGameCore->TerminateGame(-51, GameCore::Game_Status_ERROR);
                            return;
                        }
                        m_pGameCore->m_Producer.safeIn(pData);
                        qDebug() << "回答接收处理完毕!";
                    }
                    break;
                case GAME_DATA_TRANSFER_RANDOM:
                    {
                        qDebug() << "随机数接收处理中:";
                        _GameData *pData;
                        pData = new _GameData;
                        if(pData == nullptr)
                        {
                            m_pGameCore->TerminateGame(-60, GameCore::Game_Status_ERROR);
                            return;
                        }

                        pData->type = data;

                        sock->recievedData() >> pData->nRandom;

                        if(!pData->CheckGameData())
                        {
                            if(pData != nullptr)delete pData;
                            m_pGameCore->TerminateGame(-61, GameCore::Game_Status_ERROR);
                            return;
                        }
                        m_pGameCore->m_Producer.safeIn(pData);
                        qDebug() << "随机数接收处理完毕:";
                    }
                    break;

                /*
                case GAME_DATA_GAMESTART:
                    {
                        qDebug() << "游戏开始接收处理中:";
                        //传递所有武将信息！！！
                        sock->recievedData() >> data;
                        m_pGameCore->m_nMyID = data;
                        sock->recievedData() >> data;
                        m_pGameCore->playerCount = data;
                        sock->recievedData() >> m_pGameCore->m_bMaster;

                        QList<qint16> playerTypeList;
                        sock->recievedData() >> playerTypeList;

                        int i = 0;
                        for(i = 0; i < playerTypeList.count(); i++)
                        {
                            m_pGameCore->m_arrayPlayer[i].m_eJiaoSe = (_Player::JiaoSe)playerTypeList[i];
                        }
                        / *
                        QList<qint16>::iterator ii;
                        for (ii = playerTypeList.begin(); ii != playerTypeList.end(); ++ii)
                        {
                               m_pGameCore->m_arrayPlayer[i].iJiaoSe = *ii;
                        }* /

                        m_pGameCore->m_bNetPlay = true;

                        qDebug() << "StartGame:"<<m_pGameCore->m_nMyID<<m_pGameCore->playerCount<<m_pGameCore->m_bMaster;

                        sl_StartGame(m_pGameCore->playerCount,1,1,0,true);
                        qDebug() << "游戏开始接收处理完毕:";
                    }
                    break;
                case GAME_DATA_GAMEOVER:
                    {
                        sock->recievedData() >> data;
                        sl_OverGame((GameCore::_GameStatus)data);
                    }
                    break;
                */


                /*case GAME_...:    //游戏数据
                    {
                        qDebug() << "数据接收处理中:";
                        _GameData *pData;
                        pData = new _GameData;
                        if(pData == nullptr)
                        {
                            m_pGameCore->TerminateGame(-100, GameCore::Game_Status_ERROR);
                            return;
                        }


                        pData->type = data;


                        sock->recievedData() >> pData->XXXData.nData;
                        sock->recievedData() >> pData->XXXData.nDataLength;


                        pData->ChuPaiData.data = new char[pData->ChuPaiData.nDataLength];
                        if(pData->ChuPaiData.data == nullptr)
                        {
                            delete pData;
                            m_pGameCore->TerminateGame(-11, GameCore::Game_Status_ERROR);
                            return;
                        }

                        int ret = sock->recievedData().readRawData(pData->XXXData.data,pData->XXXData.nDataLength);
                        if(ret != pData->XiPaiData.nDataLength)
                        {
                            Debug(tr("读取数据出错:%1").arg(ret));
                            delete pData->ChuPaiData.data;
                            delete pData;
                            m_pGameCore->TerminateGame(-11, GameCore::Game_Status_ERROR);
                            return;
                        }

                        if(!pData->CheckGameData())
                        {
                            if(pData != nullptr)delete pData;
                            m_pGameCore->TerminateGame(-51, GameCore::Game_Status_ERROR);
                            return;
                        }
                        v->m_Producer.safeIn(pData);
                        qDebug() << "数据接收处理完毕:";
                    }
                    break;*/

                default:
                    qCritical() << (tr("[!GameManager]GAME_DATA通信 ERROR:")) << data;
                    break;
                }
            }
            break;

        default:
            qCritical() << "[!GameManager]数据 ERROR:" << data;
            break;
        }   //switch(data)

        /*
        int id;
        sock->recievedData() >> id;
        qDebug() << (QString("包ID:%1").arg(id));
        */


    }
    return;
}

void GameManager::OnGameReadyRead(TcpSocket* sock)
{
    qint16 data;

    //uint datalen = sock->recievedDataSize();
    //if(m_pGameCore->m_bMaster)
    //    qDebug() << "主机客户端接收数据大小:" << datalen;
    //else
    //    qDebug() << "副机客户端接收数据大小:" << datalen;


    //QDataStream dsData(baData);
    //while(!sock->recievedData().atEnd())
    //if(!sock->recievedData().atEnd())     //不能判断数据是否空,因为有些没有数据,比如8d类型
    {
        switch(sock->m_ucInControlByte)
        {
        case quint8(0x8c):
            qDebug() << "[GameManager]接受到加密Code:" << sock->m_listOutTransfersCode;
            while(!sock->m_listOutCodeData.isEmpty() && !sock->m_listOutTransfersCode.isEmpty())    //如果队列中有数据,则发送
                SendWithCode(sock);
            return;

        default:
            break;
        }   //switch(sock->m_ucInControlByte)


        sock->recievedData() >> data;
        switch(data)
        {
        /*case :
            {
                //int datalen = sock->recievedDataSize();
                sock->recievedData() >> data;
                switch(data)
                {
                    default:
                    break;
                }
                int i = sock->recievedData().readRawData(data,datalen);
            }
            break;
        */
        default:
            //m_pGameWindow->scene->ShowDebug(tr("主通信错误%1").arg(data));
            break;
        }   //switch(data)
    }
    return;
}


void GameManager::sl_qml_DebugButton(int button, QVariant v)
{
    //显示发送Socket的信息
    if(button == 10)
    {
        qDebug() << m_pGameSocket->sendDataValid() << m_pGameSocket->sendData().device()->pos() << m_pGameSocket->sendData().device()->bytesAvailable();
        //showHex(m_pGameSocket->getOutBlock().data(),m_pGameSocket->getOutBlock().length());
    }
    //显示发送Socket的信息
    else if(button == 20)
    {
        m_pGameSocket->sendData(0x10);
        m_pGameSocket->send(false);
    }

    //显示发送Socket的信息
    else if(button == 21)
    {
        /*
        m_pGameSocket->sendData()<<(qint16)GAME_SERVER_REQUEST
                              <<(qint16)INFO_SERVER_SERVERINFO;
        m_pUserInfo->send();
        m_pGameSocket->sendData()<<(qint16)GAME_SERVER_REQUEST
                              <<(qint16)INFO_SERVER_SERVERINFO;
        m_pUserInfo->send();
        m_pGameSocket->sendData()<<(qint16)GAME_SERVER_REQUEST
                              <<(qint16)INFO_SERVER_SERVERINFO;
        m_pUserInfo->send();
        */
    }
    else if(button == 22)
    {
        /*m_pUserInfo->connectToServer();
        m_pGameSocket->connectToHost(
                    config.configHash["SERVER_IP"],
                    config.configHash["SERVER_PORT"].toInt());
                    */
    }
    else if(button == 23)
    {
        if(m_pGameCore->m_arrayPlayer[m_pGameCore->m_nMyID].m_bTuoGuan == true)
        {
            m_pGameCore->m_arrayPlayer[m_pGameCore->m_nMyID].m_bTuoGuan = false;
        }
        else
        {
            m_pGameCore->m_arrayPlayer[m_pGameCore->m_nMyID].m_bTuoGuan = true;
            m_pGameCore->m_DianJiPai.nFlags = _BaseObject::Flag_Null;
            m_pGameCore->sl_UserActionFinished();
        }
    }
}

QObject* GameManager::wordLib() const
{
    return m_pWordLib;
}
